import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';

interface UEditorProps {
    value?: string;
    onChange?: (content: string) => void;
    style?: React.CSSProperties;
    config?: Record<string, any>;
}

declare global {
    interface Window {
        UE: any;
    }
}

const UEditor = forwardRef((props: UEditorProps, ref) => {
    const editorContainer = useRef<HTMLDivElement>(null);
    const ueInstance = useRef<any>(null);
    const isInitializing = useRef(false);
    const ignoreChangeRef = useRef(false);
    const lastSavedSelection = useRef<any>(null);
    const { value, onChange, style, config = {} } = props;
    const saveSelection = () => {
        if (ueInstance.current && ueInstance.current.isReady) {
            try {
                const range = ueInstance.current.selection.getRange();
                lastSavedSelection.current = range;
            } catch (error) {
                console.warn('保存选区失败:', error);
                lastSavedSelection.current = null;
            }
        }
    };

    const restoreSelection = () => {
        if (ueInstance.current && ueInstance.current.isReady && lastSavedSelection.current) {
            try {
                ueInstance.current.selection.getRange(lastSavedSelection.current);
                ueInstance.current.selection.select();
            } catch (error) {
                console.warn('恢复选区失败:', error);
            }
        }
    };
    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
        getContent: () => ueInstance.current?.getContent() || '',
        setContent: (content: string) => {
            if (ueInstance.current && ueInstance.current.isReady) {
                // 保存当前选区
                lastSavedSelection.current = ueInstance.current.selection.getRange();
                ueInstance.current.setContent(content);
            }
        },
        getPlainText: () => ueInstance.current?.getPlainTxt() || '',
        saveSelection,
        restoreSelection,

    }));

    // 加载脚本
    const loadScript = (src: string) => {
        return new Promise((resolve, reject) => {
            if (document.querySelector(`script[src="${src}"]`)) {
                return resolve(true);
            }

            const script = document.createElement('script');
            script.src = src;
            script.onload = resolve;
            script.onerror = () => reject(new Error(`加载失败: ${src}`));
            document.body.appendChild(script);
        });
    };

    // 初始化编辑器
    const initEditor = async () => {
        if (isInitializing.current || !editorContainer.current) return;
        isInitializing.current = true;

        try {
            // 确保 UE 已加载
            if (!window.UE) {
                await Promise.all([
                    loadScript('/UEditor/ueditor.config.js'),
                    loadScript('/UEditor/ueditor.all.min.js'),
                    loadScript('/UEditor/lang/zh-cn/zh-cn.js')
                ]);
            }

            // 检查容器是否存在于 DOM 中
            if (window.UE && editorContainer.current && document.contains(editorContainer.current)) {
                // 如果已有实例先销毁
                safeDestroyEditor();

                // 确保容器有ID
                if (!editorContainer.current.id) {
                    editorContainer.current.id = `ueditor-${Date.now()}`;
                }

                const editorConfig = {
                    // 上传配置（关键修改部分）
                    serverUrl: '/pc/common/upload', // 确保这是正确的后端接口路径
                    imageActionName: "uploadimage",
                    imageFieldName: "upfile",
                    imageMaxSize: 2 * 1024 * 1024, // 2MB
                    imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
                    imageCompressEnable: true,
                    imageCompressBorder: 1600,
                    imageUrlPrefix: "", // 根据实际部署情况设置
                    imagePathFormat: "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",

                    initialFrameWidth: '100%',
                    initialFrameHeight: 200,
                    UEDITOR_HOME_URL: '/UEditor/',
                    //跨域配置
                    crossDomain: true,
                    withCredentials: true,
                    ...config,
                };

                ueInstance.current = window.UE.getEditor(editorContainer.current.id, editorConfig);

                ueInstance.current.ready(() => {
                    // 标记编辑器已准备好
                    ueInstance.current.isReady = true;
                    ueInstance.current.setOpt({
                        imageActionName: "uploadimage",
                        imageFieldName: "upfile",
                        imageMaxSize: 2048000,
                        imageAllowFiles: [".png", ".jpg", ".jpeg"],
                        imageUrlPrefix: "",
                        imagePathFormat: "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
                    });

                    // 设置初始内容
                    if (value) {
                        ueInstance.current.setContent(value);
                    }

                    // 监听内容变化
                    ueInstance.current.addListener('contentChange', () => {
                        if (!ueInstance.current || !ueInstance.current.isReady) return;

                        // 忽略由程序触发的变更
                        if (ignoreChangeRef.current) {
                            ignoreChangeRef.current = false;
                            return;
                        }

                        const content = ueInstance.current.getContent();
                        onChange?.(content);

                        // 保存当前选区
                        lastSavedSelection.current = ueInstance.current.selection.getRange();
                    });
                });
            }
        } catch (error) {
            console.error('UEditor 初始化失败:', error);
        } finally {
            isInitializing.current = false;
        }
    };

    // 安全销毁编辑器
    const safeDestroyEditor = () => {
        if (!ueInstance.current) return;

        try {
            // 1. 移除事件监听
            ueInstance.current.removeListener?.('contentChange');

            // 2. 删除编辑器实例
            if (window.UE?.instances[ueInstance.current.key]) {
                window.UE.delEditor(ueInstance.current.key);
            }

            // 3. 清除引用
            ueInstance.current = null;
        } catch (error) {
            console.warn('UEditor 销毁警告:', error);
        }
    };

    // 组件挂载时初始化
    useEffect(() => {
        initEditor();

        return () => {
            safeDestroyEditor();
        };
    }, []);
    useEffect(() => {
        if (!ueInstance.current?.isReady || value === undefined) return;

        const currentContent = ueInstance.current.getContent();
        if (value !== currentContent) {
            ignoreChangeRef.current = true;
            saveSelection();
            ueInstance.current.setContent(value);
            setTimeout(() => restoreSelection(), 50);
        }
    }, [value]);
    // 同步 value 变化
    useEffect(() => {
        if (!ueInstance.current?.isReady || value === undefined) return;

        const currentContent = ueInstance.current.getContent();
        if (value !== currentContent) {
            // 标记变更来源，避免触发contentChange
            ignoreChangeRef.current = true;

            // 保存当前选区
            const currentSelection = ueInstance.current.selection.getRange();

            // 更新内容
            ueInstance.current.setContent(value);

            // 优先恢复之前的选区，如果没有则恢复当前选区
            if (lastSavedSelection.current) {
                ueInstance.current.selection.setRange(lastSavedSelection.current);
            } else if (currentSelection) {
                ueInstance.current.selection.setRange(currentSelection);
            }
        }
    }, [value]);

    return (
        <div
            ref={editorContainer}
            style={{
                ...style,
                minHeight: '300px',
                boxSizing: 'border-box'
            }}
        />
    );
});

export default UEditor;
